import { toast } from '../../utils/expendApi'
import { setStorage } from '../../utils/storage'
import { reqLoginApi, reqUserInfoApi } from '../../api/user'
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { userStore } from '../../stores/userstore'
import { debounce } from 'miniprogram-licia'
Page({

  data: {

  },
  login: debounce(function () {
    // 获取临时登录凭证
    wx.login({
      success: async ({code}) => {
        if(code) {
          const { data:{token} } = await reqLoginApi(code)
          setStorage('token', token)
          this.setToken(token)
          // 获取用户信息
          this.getUserInfo()
          wx.navigateBack()
        } else {
          toast({ title: '授权失败,请重新授权' })
        }
      },
    })
  }, 500),
  // 获取用户信息
  async getUserInfo () {
    const { data } = await reqUserInfoApi()
    setStorage('userInfo', data)
    this.setUserInfo(data)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取userstore
    this.storeBindings = createStoreBindings(this, {
      store: userStore,
      fields: ['token', 'userInfo'],
      actions: ['setToken', 'setUserInfo']
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.storeBindings.destroyStoreBindings()
  }
})